#include "InputManager.h"
#include "KeyboardEvent.h"
#include "MouseEvent.h"

namespace Lame3d
{
	InputManager::InputManager(const DisplayManager &d)
			: mouseLocation(.5, .5), mouseXDiff(1.0/d.CurrentConfig().Width*(d.CurrentConfig().Width/float(d.CurrentConfig().Height))), mouseYDiff(1.0/d.CurrentConfig().Height), displayManager(d)
	{
	}
	
	InputManager::~InputManager()
	{
	}
	
	UIManager& InputManager::UI()
	{
		return uiManager;
	}
	
	const UIManager& InputManager::UI() const
	{
		return uiManager;
	}
	
	KeyboardManager& InputManager::Keyboard()
	{
		return keyboard;
	}
	
	void InputManager::Handle()
	{
		int xDisp(0);
		int yDisp(0);
		SDL_Event evt;
		while(SDL_PollEvent(&evt) != 0) {
			if(evt.type == SDL_KEYDOWN || evt.type == SDL_KEYUP) {
				KeyEvent evt2(evt.key);
				handleKeyEvent(evt2);
			} else if(evt.type == SDL_MOUSEBUTTONDOWN || evt.type == SDL_MOUSEBUTTONUP) {
				MouseClickEvent evt2(&evt.button, mouseLocation);
				handleMouseClickEvent(evt2);
			} else if(evt.type == SDL_MOUSEMOTION) {
				SDL_MouseMotionEvent *evt2 = &evt.motion;
				xDisp += evt2->xrel;
				yDisp += evt2->yrel;
			}
		}
		
		Point2d mouseDiff(xDisp*mouseXDiff, -yDisp*mouseYDiff);
		Point2d newMouseLoc(mouseLocation);
		newMouseLoc += mouseDiff;
		bool boundsX(false), boundsY(false);
		if(newMouseLoc[0] > displayManager.Ratio()) {
			boundsX = true;
			newMouseLoc[0] = displayManager.Ratio();
		} else if(newMouseLoc[0] < 0) {
			boundsX = true;
			newMouseLoc[0] = 0;
		}
		if(newMouseLoc[1] > 1.0) {
			boundsY = true;
			newMouseLoc[1] = 1.0;
		} else if(newMouseLoc[1] < 0) {
			boundsY = true;
			newMouseLoc[1] = 0;
		}
		mouseLocation = newMouseLoc;
		
		MouseMotionEvent evt2(mouseLocation, mouseDiff, boundsX, boundsY);
		handleMouseMotionEvent(evt2);
	}
	
	const Point2d& InputManager::MouseLocation() const
	{
		return mouseLocation;
	}
	
	void InputManager::handleKeyEvent(KeyEvent &e)
	{
		//printf("Handling keyboard evt..\n");
		// UI layer gets first dibs on keyboard events
		if(!uiManager.Handle(e)) {
			keyboard.Handle(e);
		}
	}
	
	void InputManager::handleMouseClickEvent(MouseClickEvent &e)
	{
		printf("Click at %f, %f\n", e.Location()[0], e.Location()[1]);
		uiManager.Handle(e);
	}
	
	void InputManager::handleMouseMotionEvent(MouseMotionEvent &e)
	{
		//printf("Motion with %f, %f\n", e.Motion()[0], e.Motion()[1]);
		uiManager.Handle(e);
	}
}

// eof //
